<!--叠加柱状图-->
<template>
  <div class="stacked-bar-chart w-full h-full" ref="stackedBarChart"></div>
</template>

<script lang="ts" setup>
import { defineComponent, markRaw, onMounted, onBeforeUnmount, ref, watch } from 'vue';
import * as echarts from 'echarts';
import { sleep } from '@/utils/sleep';

defineComponent({ name: 'StackedBarChart' });

const props = defineProps({
  echartsData: {
    type: Object,
    default: () => {
      return { label: [], data: [] };
    },
  },
});

const stackedBarChart = ref();
const myChart = ref<any>(null);

function initEcharts(echartsData: any) {
  myChart.value = markRaw(echarts.init(stackedBarChart.value));

  let series: any[] = [];
  const arr = echartsData.data || [];
  arr.forEach((item: any) => {
    series.push({
      name: item.name,
      type: 'bar',
      stack: 'all',
      barWidth: 12,
      data: item.value,
    });
  });

  const option = {
    tooltip: {
      backgroundColor: 'rgba(0,150,236,0.6)',
      textStyle: {
        color: '#fff',
      },
      formatter: '{a} <br/>{b} : {c}%'
    },
    legend: {
      itemHeight: 3,
      itemWidth: 28,
      icon: 'rect',
      right: 0,
      top: '15',
      textStyle: {
        color: '#fff',
      },
    },
    color: ['#0249B1', '#FFFE00', '#FE7E00', '#FF0204'],
    grid: {
      top: '60',
      bottom: '20',
    },
    xAxis: {
      axisLine: {
        lineStyle: {
          color: '#fff',
        },
      },
      axisLabel: {
        textStyle: {
          color: 'rgba(235, 243, 255, 0.75)',
        },
      },
      show: true,
      type: 'value',
      axisTick: {
        show: false,
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#5D7AA6',
        },
      },
    },
    yAxis: {
      data: echartsData.label || [],
      axisLine: {
        lineStyle: {
          color: '#5D7AA6',
        },
      },
      axisLabel: {
        textStyle: {
          color: 'rgba(235, 243, 255, 0.75)',
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        show: false,
      },
    },
    series,
  };
  myChart.value.setOption(option, true);
  window.addEventListener('resize', () => {
    if (myChart.value) myChart.value.resize();
  });
}

function destroyEcharts() {
  if (myChart.value) {
    myChart.value.dispose();
    myChart.value = null;
  }
}

onMounted(() => {
  watch(
    () => props.echartsData,
    async (val: any) => {
      destroyEcharts();
      await sleep(500);
      if (stackedBarChart.value) initEcharts(val);
    },
    { immediate: true, deep: true }
  );
});

onBeforeUnmount(() => {
  destroyEcharts();
});
</script>

<style scoped></style>
